const baseURL: string = "https://hzh.woide.top/";
// const baseURL: string = "";
import Axios from "axios";
import type { Method } from "axios";
import { message } from "ant-design-vue";
import { useRouter } from "vue-router";

const request = (url?: string, method?: Method, data?: any): Promise<any> => {
  const router = useRouter();
  const userInfo =
    JSON.parse(window.localStorage.getItem("userInfo") || "{}") || {};
  return new Promise((resolve, reject) => {
    Axios({
      url: baseURL + url,
      headers: {
        Authorization: userInfo.access_token
          ? userInfo.token_type + " " + userInfo.access_token
          : "",
      },
      method: method || "GET",
      data: data,
    })
      .then((res) => {
        
        
        if (res.data.code === 2) {
          Axios.get("com/refresh_token", {
            headers: {
              Authorization: userInfo
                ? userInfo.token_type + " " + userInfo.refresh_token
                : "",
            },
          }).then((refresh) => {
            if (refresh.data.code != 0) return message.error({ content: refresh.data.msg });
            const { access_token, refresh_token } = refresh.data["0"];
            userInfo.access_token = access_token;
            userInfo.refresh_token = refresh_token;
            window.localStorage.setItem("userInfo", JSON.stringify(userInfo));
          });
          router.push({ path: '/login' })
        } else if (res.data.code === 500) {
          router.push({ path: '/login' })
        }
        resolve(res);
      })
      .catch((err) =>{
        
      });
  });
};

export default request;
